package com.example.callservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.Adapter.DistrictAdapter;
import com.example.Adapter.RoadAdapter;
import com.example.Dialog.DialogPanelList;
import com.example.googlemap.CustomItemizedOverlay;
import com.example.object.Coordinate;
import com.example.object.District;
import com.example.object.ElectricPanels;
import com.example.object.Luminaires;
import com.example.object.Roads;
import com.example.ultil.Ultil;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class GMap extends MapActivity implements OnClickListener {

	View layoutPopUp;
	MapView mapView;
	private DistrictAdapter districtAdapter;
	private RoadAdapter roadAdapter;
	private PopupWindow popupWindow;
	EditText txtSearch;

	Button btnOk;
	Button btnCancel;
	Button btnAlarm;
	Button btnSearch;
	Button btnSearchAdvance;
	Button btnCurPositon;

	Spinner spDistrict;
	Spinner spRoad;
	Spinner spPanel;

	ArrayList<Coordinate> lstCoor = null;
	ArrayList<District> lstDistrict = new ArrayList<District>();

	// Socket
	String IP_ADDRESS = "112.78.11.140";
	int PORT = 1503;
	String rsSocket = "";
	OverlayItem overlayitem;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.google_map);

		mapView = (MapView) findViewById(R.id.map_view);
		btnAlarm = (Button) findViewById(R.id.btnAlarm);
		btnSearch = (Button) findViewById(R.id.btnSearch);
		btnSearchAdvance = (Button) findViewById(R.id.btnSearchAdvance);

		btnSearch.setOnClickListener(this);
		btnSearchAdvance.setOnClickListener(this);
		btnAlarm.setOnClickListener(this);
		btnCurPositon = (Button) findViewById(R.id.btnGPS);
		btnCurPositon.setOnClickListener(this);

		mapView.setBuiltInZoomControls(true);
		txtSearch = (EditText) findViewById(R.id.txtSearch);
		drawMap(Ultil.lstElectricPanel, Ultil.lstLuminaire);
		// new getSocket().execute();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public void drawMap(ArrayList<ElectricPanels> lstElectricPanel, ArrayList<Luminaires> lstlLuminaires) {
		if (lstElectricPanel.size() > 0) {
			for (int i = 0; i < Ultil.lstElectricPanel.size(); i++) {
				int latitude = (int) (Float.parseFloat(Ultil.lstElectricPanel
						.get(i).getLat()) * 1000000);
				int longitude = (int) (Float.parseFloat(Ultil.lstElectricPanel
						.get(i).getLong()) * 1000000);
				List<Overlay> mapOverlays = mapView.getOverlays();
				mapView.setBuiltInZoomControls(true);
				Drawable drawable = this.getResources().getDrawable(
						R.drawable.panel_on);
				CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
						drawable, this, i);
				GeoPoint point = new GeoPoint(latitude, longitude);
				Log.e("acc", latitude + "," + longitude);
				overlayitem = new OverlayItem(point, "Hello",
						"I'm in Athens, Greece!");
				itemizedOverlay.addOverlay(overlayitem);
				mapOverlays.add(itemizedOverlay);
				MapController mapController = mapView.getController();
				mapController.animateTo(point);
				mapController.setZoom(12);

			}
		}
		if (lstlLuminaires.size() > 0) {
			for (int j = 0; j < Ultil.lstLuminaire.size();j++) {
				int latitude = (int) (Float.parseFloat(Ultil.lstLuminaire
						.get(j).getLat()) * 1000000);
				int longitude = (int) (Float.parseFloat(Ultil.lstLuminaire
						.get(j).getLong()) * 1000000);
				List<Overlay> mapOverlays = mapView.getOverlays();
				mapView.setBuiltInZoomControls(true);
				Drawable drawable = this.getResources().getDrawable(
						R.drawable.panel_on);
				CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
						drawable, this, j);
				GeoPoint point = new GeoPoint(latitude, longitude);
				overlayitem = new OverlayItem(point, "Hello",
						"I'm in Athens, Greece!");
				itemizedOverlay.addOverlay(overlayitem);
				mapOverlays.add(itemizedOverlay);
				MapController mapController = mapView.getController();
				mapController.animateTo(point);
				mapController.setZoom(12);

			}
		}

	}

	public void drawMapPanel(ElectricPanels electricPanel, int pos) {
		if (dialogPanel.isShowing()) {
			dialogPanel.dismiss();
		}
		// mapView.postInvalidate();

		int latitude = (int) (Float.parseFloat(electricPanel.getLat()) * 1000000);
		int longitude = (int) (Float.parseFloat(electricPanel.getLong()) * 1000000);
		List<Overlay> mapOverlays = mapView.getOverlays();
		mapView.setBuiltInZoomControls(true);
		Drawable drawable = this.getResources().getDrawable(
				R.drawable.panel_on);
		CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
				drawable, this, electricPanel);
		GeoPoint point = new GeoPoint(latitude, longitude);
		Log.e("acc", latitude + "," + longitude);
		overlayitem = new OverlayItem(point, "Hello", "I'm in Athens, Greece!");
		itemizedOverlay.addOverlay(overlayitem);
		mapOverlays.add(itemizedOverlay);
		MapController mapController = mapView.getController();
		mapController.animateTo(point);
		mapController.setZoom(16);
		mapView.invalidate();

	}

	@SuppressWarnings("deprecation")
	private void initiatePopupWindow() {
		try {

			LayoutInflater inflater = (LayoutInflater) GMap.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			layoutPopUp = inflater.inflate(R.layout.popup, null);
			popupWindow = new PopupWindow(layoutPopUp,
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true);

			spDistrict = (Spinner) layoutPopUp.findViewById(R.id.spDistrict);
			spRoad = (Spinner) layoutPopUp.findViewById(R.id.spRoad);
			spPanel = (Spinner) layoutPopUp.findViewById(R.id.spPanel);
			districtAdapter = new DistrictAdapter(getApplicationContext(),
					Ultil.lstDistrict);

			spDistrict.setAdapter(districtAdapter);
			spDistrict.setOnItemSelectedListener(new OnItemSelectedListener() {

				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int pos, long arg3) {
					// TODO Auto-generated method stub

					ArrayList<Roads> lstRoads = districtAdapter
							.getListRoadByIdDistrict(pos);
					roadAdapter = new RoadAdapter(GMap.this, lstRoads);
					spRoad.setAdapter(roadAdapter);
				}

				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub

				}
			});
			// spDistrict.set
			btnOk = (Button) layoutPopUp.findViewById(R.id.btnOk);
			btnOk.setOnClickListener(this);
			btnCancel = (Button) layoutPopUp.findViewById(R.id.btnCancel);
			btnCancel.setOnClickListener(this);
			popupWindow.showAsDropDown(layoutPopUp, 0, 0 + 40);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public ArrayList<Roads> getLstRoadbyDistrict(String idDistrict) {

		ArrayList<Roads> lstRoad = new ArrayList<Roads>();
		for (int i = 0; i > Ultil.lstElectricPanel.size(); i++) {
			for (int j = 0; j > Ultil.lstDistrict.size(); j++)
				if (Ultil.lstDistrict.get(i).equals(idDistrict)) {
					Roads road = new Roads();
					road.setRoad_ID(Ultil.lstElectricPanel.get(i).getRoad_ID());
					road.setRoad_Name(Ultil.lstElectricPanel.get(i)
							.getRoad_Name());
					lstRoad.add(road);
				}
		}
		return lstRoad;
	}

	DialogPanelList dialogPanel;

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnAlarm:
			initiatePopupWindow();
			break;
		case R.id.btnCancel:
			popupWindow.dismiss();
			break;
		case R.id.btnSearch:
			dialogPanel = new DialogPanelList(GMap.this, GMap.this,
					Ultil.lstElectricPanel, txtSearch.getText().toString());
			dialogPanel.show();
			break;
		case R.id.btnGPS:
			LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

			LocationListener mlocListener = new MyLocationListener();

			mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
					0, mlocListener);
			break;
		default:
			break;
		}
	}

	private class getSocket extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... params) {
			Socket csSocket = null;
			PrintWriter out = null;
			BufferedReader in = null;
			try {

				csSocket = new Socket("112.78.11.140", 1503);
				out = new PrintWriter(csSocket.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(
						csSocket.getInputStream()));
			} catch (UnknownHostException e) {
				System.err.println("Don't know about host: localhost.");
				System.exit(1);
			} catch (IOException e) {
				System.err
						.println("Couldn't get I/O for the connection to:localhost.");
				System.exit(1);
			}
			BufferedReader stdIn = new BufferedReader(new InputStreamReader(
					System.in));
			int fromServer;
			String fromUser;
			String temp;
			int bufSize = 0;
			try {
				bufSize = csSocket.getReceiveBufferSize();
			} catch (SocketException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			char[] cbuf = new char[bufSize];
			Boolean first = true;
			while (true) {
				try {
					fromServer = in.read(cbuf);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				char[] tempChar = new char[cbuf.length];
				temp = new String(cbuf);
				rsSocket = temp;
				// System.out.println("Server: " + temp);
				// System.out.println("Server: " + rsSocket);
				Log.e("SERVER:SOCKET", temp);
				if (temp.contains("XNTV") && first == true) {

					fromUser = Ultil.SERVERNAME;//
					out.println(fromUser);
				}
				first = false;
			}

		}

		protected void onPostExecute(String results) {
			if (results != null) {

			}
		}
	}

	public class MyLocationListener implements LocationListener

	{

		@Override
		public void onLocationChanged(Location loc)

		{

			loc.getLatitude();

			loc.getLongitude();

			String Text = "My current location is: " +

			"Latitud = " + loc.getLatitude() +

			"Longitud = " + loc.getLongitude();

			Toast.makeText(getApplicationContext(),

			Text,

			Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onProviderDisabled(String provider)

		{

			Toast.makeText(getApplicationContext(),

			"Gps Disabled",

			Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onProviderEnabled(String provider)

		{

			Toast.makeText(getApplicationContext(),

			"Gps Enabled",

			Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras)

		{

		}

	}/* End of Class MyLocationListener */

}
